﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using FlickrMe.Auth;
using System.Reflection;
using System.IO;

namespace FlickrMe.browser
{
    class FlickrBrowser : Form
    {
        private WebBrowser webBrowser1;
        private String url;
        private AutenticationManager aman;

        private String successUrl = "http://www.flickr.com/services/auth/";
    
        public FlickrBrowser(AutenticationManager aman, String url)
        {
            this.aman = aman;

            InitializeComponent();

            showIndexFile();

            NavigateToURL(url);
        }


        private void showIndexFile()
        {
            string path = Path.GetDirectoryName(
                Assembly.GetExecutingAssembly().Location);

            String url = path + "\\index.htm";
            NavigateToURL(url);
        }

        private void NavigateToURL(String url)
        {
            Uri uri = new Uri(url);
            this.webBrowser1.Navigate(uri);
            this.url = url;
        }


        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FlickrBrowser));
            this.webBrowser1 = new System.Windows.Forms.WebBrowser();
            this.SuspendLayout();
            // 
            // webBrowser1
            // 
            this.webBrowser1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.webBrowser1.Location = new System.Drawing.Point(0, 0);
            this.webBrowser1.MinimumSize = new System.Drawing.Size(20, 20);
            this.webBrowser1.Name = "webBrowser1";
            this.webBrowser1.Size = new System.Drawing.Size(797, 635);
            this.webBrowser1.TabIndex = 0;
            this.webBrowser1.Navigated += new System.Windows.Forms.WebBrowserNavigatedEventHandler(this.webBrowser1_Navigated);
            // 
            // FlickrBrowser
            // 
            this.ClientSize = new System.Drawing.Size(797, 635);
            this.Controls.Add(this.webBrowser1);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Name = "FlickrBrowser";
            this.ResumeLayout(false);

        }

        private void webBrowser1_Navigated(Object obj, WebBrowserNavigatedEventArgs args) 
        {
            if (isAuthenticationComplete(args.Url.AbsoluteUri)) {
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
        }

        private bool isAuthenticationComplete(String url)
        {
            // Standard authentication done
            if (url.Equals(this.successUrl)) return true;

            if (url.Equals(this.url) && aman.IsAuthenticated()) return true;

            return false;
          
        }


    }
}
